package com.qqt.csr.message.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qqt.csr.common.acl.auth.resp.AuthInfoDTO;
import com.qqt.csr.common.session.SessionContextHolder;
import com.qqt.csr.common.vo.req.RequestHeader;
import com.qqt.csr.message.enums.ActionType;
import com.qqt.csr.message.enums.ReadFlag;
import com.qqt.csr.message.response.MessageNotifyResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qqt.csr.message.entity.MessageNotify;
import com.qqt.csr.message.mapper.MessageNotifyMapper;

@Slf4j
@Service
public class MessageNotifyService extends ServiceImpl<MessageNotifyMapper, MessageNotify> {

    /**
     * 读取未读消息 返回并置为已读
     * @return {@link List<MessageNotifyResponse>} 未读消息
     */
    public List<MessageNotifyResponse> readNotify() {
        // 获取当前用户id
        Long currentUserId = getCurrentUserId();
        // 获取当前用户权限列表
        List<String> permissionList = getPermissionList();
        if (currentUserId == null || permissionList == null || permissionList.isEmpty()) {
            return Collections.emptyList();
        }
        // 获取未读消息
        List<MessageNotify> unreadList = listByRecipientIdAndUnread(currentUserId);
        if (unreadList.isEmpty()) {
            return Collections.emptyList();
        }
        // 处理未读消息 权限问题 仅处理非管理员权限
        if (!permissionList.contains("*:*:*")) {
            processUnreadMessages(unreadList, permissionList);
        }
        // 更新未读消息为已读
        updateUnreadMessagesAsRead(unreadList);
        // 转换为响应对象
        return BeanUtil.copyToList(unreadList, MessageNotifyResponse.class);
    }

    /**
     * 根据接收人id获取未读消息
     * @param recipientId {@link Long} 接收人id
     * @return {@link List<MessageNotify>} 未读消息
     */
    public List<MessageNotify> listByRecipientIdAndUnread(Long recipientId) {
        if (recipientId == null) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<MessageNotify> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MessageNotify::getRecipientId, recipientId);
        wrapper.eq(MessageNotify::getReadFlag, ReadFlag.UNREAD.getValue());
        return this.list(wrapper);
    }

    /**
     * 获取当前用户id
     * @return {@link Long} 当前用户id
     */
    private Long getCurrentUserId() {
        return Optional.ofNullable(SessionContextHolder.getHeaderInfo())
                .map(RequestHeader::getUserId)
                .orElse(null);
    }

    /**
     * 获取当前用户权限列表
     * @return {@link List<String>} 权限列表
     */
    private List<String> getPermissionList() {
        return Optional.ofNullable(SessionContextHolder.getHeaderInfo())
                .map(RequestHeader::getAuthInfoDTO)
                .map(AuthInfoDTO::getPermissionList)
                .orElse(Collections.emptyList());
    }

    /**
     * 处理未读消息 权限问题
     * @param unreadList {@link List<MessageNotify>} 未读消息列表
     * @param permissionList {@link List<String>} 权限列表
     */
    private void processUnreadMessages(List<MessageNotify> unreadList, List<String> permissionList) {
        unreadList.stream()
                .filter(messageNotify -> StrUtil.isNotBlank(messageNotify.getExt()))
                .filter(messageNotify -> {
                    String permission = getPermissionFromExt(messageNotify.getExt());
                    return StrUtil.isNotBlank(permission) && !permissionList.contains(permission);
                })
                .forEach(messageNotify -> messageNotify.setActionType(ActionType.ONLY_POP_UPS.getValue()));
    }

    /**
     * 从扩展字段中获取权限
     * @param ext {@link String} 扩展字段
     * @return {@link String} 权限
     */
    private String getPermissionFromExt(String ext) {
        try {
            return JSONUtil.parseObj(ext).getStr("permission", "");
        } catch (Exception e) {
            // 处理解析异常，例如返回空字符串
            return "";
        }
    }

    /**
     * 更新未读消息为已读
     * @param unreadList {@link List<MessageNotify>} 未读消息列表
     */
    private void updateUnreadMessagesAsRead(List<MessageNotify> unreadList) {
        unreadList.forEach(item -> item.setReadFlag(ReadFlag.READ.getValue()));
        this.updateBatchById(unreadList);
    }
}
